/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveReplaceFormsDesign: CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_SourceFormsToolURI;
		private string[] m_TargetFormsToolURIs;
		
		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveReplaceFormsDesign(i_Arguments));
		}
	
		public GrooveReplaceFormsDesign(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveReplaceFormsDesign[PARAMS...]";
			base.HelpMessage = 
				"GrooveReplaceFormsDesign\r\n\t" + 
				"Replaces form design for specified tool(s)\r\n" +
				"Parameters:\r\n\t" +
				"/SourceFormsTool=    The Web Services URI for the Groove forms tool\r\n\t" +
				"/TargetFormsTools=   Comma delimited Web Services URIs for Groove forms tools\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"[/V                  Verbose output\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;

			m_SourceFormsToolURI = base.GetParameterValue("SourceFormsTool");
			if (System.String.IsNullOrEmpty(m_SourceFormsToolURI))
			{
				base.DisplayUsage("You must specify a source forms tool.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			string TargetFormsToolURI = base.GetParameterValue("TargetFormsTools");
			if (System.String.IsNullOrEmpty(TargetFormsToolURI))
			{
				base.DisplayUsage("You must specify target forms tool(s).");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_TargetFormsToolURIs = TargetFormsToolURI.Split(new char[]{','});

			//  The format for a Tool URI is:
			//    "/GWS/Groove/2.0/Tools/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2/ToolContainer/vk2xck8tanv5i"
			//
			//  The format for a Space URI is:
			//    "/GWS/Groove/2.0/Spaces/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2"

			string[] SourceFormsToolURIParts = m_SourceFormsToolURI.Split(new char[]{'/'});
			m_SpaceURI = "/GWS/Groove/2.0/Spaces/grooveTelespace/" + SourceFormsToolURIParts[6];

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Space Space = null;

			try
			{
				Space = base.Identity.OpenSpace(m_SpaceURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
				throw Exception;
			}

			GrooveWebServicesV12Helpers.Tool SourceTool = null;
			
			try
			{
				SourceTool = (GrooveWebServicesV12Helpers.Tool)Space.OpenTool(m_SourceFormsToolURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open source forms tool: " + Exception.Message);
				throw Exception;
			}

            if (SourceTool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool SourceFormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)SourceTool;

                string[] ReplacedFormsToolsURIs = null;

                try
                {
                    ReplacedFormsToolsURIs = SourceFormsTool.ReplaceDesign(m_TargetFormsToolURIs);
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to replace design: " + Exception.Message);
                    throw Exception;
                }

                //  Check if all target forms tools had design replaced
                if (ReplacedFormsToolsURIs.Length != m_TargetFormsToolURIs.Length)
                {
                    foreach (string TargetFormsToolURI in m_TargetFormsToolURIs)
                    {
                        bool FoundMatch = false;

                        foreach (string ReplacedFormsToolURI in ReplacedFormsToolsURIs)
                        {
                            if (ReplacedFormsToolURI == TargetFormsToolURI)
                            {
                                FoundMatch = true;
                                break;
                            }
                        }

                        if (!FoundMatch)
                            base.StandardError.WriteLine("Replace failed for " + TargetFormsToolURI);
                    }

                    return CommandUtils.UtilBase.CheckResult.Failed;
                }
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool SourceFormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)SourceTool;

                System.Collections.Generic.List<string> ReplacedFormsToolURIList = new System.Collections.Generic.List<string>();

                foreach (string TargetFormsToolURI in m_TargetFormsToolURIs)
                {
                    try
                    {
                        SourceFormsTool.ReplaceDesign(TargetFormsToolURI);
                        ReplacedFormsToolURIList.Add(TargetFormsToolURI);
                    }
                    catch (System.Exception Exception)
                    {
                        base.StandardError.WriteLine("Unable to replace design for '" + TargetFormsToolURI + "': " + Exception.Message);

                        foreach (string TargetFormsToolURI2 in m_TargetFormsToolURIs)
                        {
                            if (!ReplacedFormsToolURIList.Contains(TargetFormsToolURI2) && (TargetFormsToolURI2 != TargetFormsToolURI))
                                base.StandardError.WriteLine("Replace not performed for " + TargetFormsToolURI2);
                        }

                        throw Exception;
                    }
                }
            }

			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}
	}
}